package com.ooqiu.gaming.ui.article_detail;

import android.graphics.Bitmap;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.GamingApi;
import com.ooqiu.gaming.api.entities.ArticleDetailRes;
import com.ooqiu.gaming.base.BaseShareActivity;
import com.ooqiu.gaming.components.retrofit.progress.ProgressSubscriber;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.main.thread.index.content.IndexContentAdapter;
import com.ooqiu.gaming.utils.LogUtil;
import com.ooqiu.gaming.view.H5Callback;
import com.ooqiu.gaming.view.JockeyJsWebView;
import com.ooqiu.gaming.view.ToastUtil;
import com.ooqiu.gaming.view.Topbar;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebView;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@Route(path = VideoDetailActivity.PATH)
public class VideoDetailActivity extends BaseShareActivity implements H5Callback {
    public static final String PATH = "/gn/video/detail";
    @BindView(R.id.topbar)
    Topbar mTopbar;
    @BindView(R.id.web_x5)
    JockeyJsWebView mWebX5;
    @BindView(R.id.statue_view)
    FrameLayout mStatueView;

    GamingApi mGamingApi;
    UserStorage mUserStorage;
    @Autowired
    int news_id;

    ArticleDetailRes mArticleDetailRes;

    @Override
    public int initContentView() {
        return R.layout.activity_video_datail;
    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mGamingApi = getApplicationComponent().getGamingApi();
        mUserStorage = getApplicationComponent().getUserStorage();
    }

    @Override
    public void initUiAndListener() {
        mWebX5.loadUrl("file:///android_asset/dist/video_arc.html");
        mWebX5.setCallback(this);
        mWebX5.initJockey();
//        mWebX5.setOnScrollChangedCallback(this);
        mWebX5.addJavascriptInterface(new AndroidBridge(this), "AndroidBridge");


        mTopbar.setOnMenuClickListener(new View.OnClickListener() {
          @Override
        public void onClick(View v) {
              if (mArticleDetailRes != null) {
                  collect();
              }
        }
    });

        showLoading();
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return mTopbar;
    }

    @Override
    protected View statusLayoutId() {
        return mStatueView;
    }

    @Override
    public void doPerform(Map<Object, Object> map) {
        LogUtil.e("doPerform");
    }

    @Override
    public void onPageFinished(WebView webView, String str) {
        LogUtil.e("onPageFinished");
        if (mArticleDetailRes == null) {
            fetchVideoDetail(news_id);
        }

    }

    @Override
    public void onPageStarted(WebView webView, String str, Bitmap bitmap) {
//        LogUtil.e("onPageStarted");
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//        LogUtil.e("onReceivedError");
    }

    @Override
    public void setJockeyEvents() {
        LogUtil.e("setJockeyEvents");
    }

    @Override
    public void openBrowser(String url) {
        LogUtil.e("openBrowser " + url);
    }


    @Override
    public void onRetryClick() {
        fetchVideoDetail(news_id);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mArticleDetailRes != null && mUserStorage.isLogin()) {
            fetchCollectStatue();
        }
    }

    private void fetchCollectStatue() {
        mGamingApi.fetchCollectStatue(news_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<CollectStatue>(mContext) {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(CollectStatue collectStatue) {
                        mArticleDetailRes.setIs_collect(collectStatue.getIs_collect());
                        mArticleDetailRes.setIs_like(collectStatue.getIs_like());
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private void fetchVideoDetail(int news_id) {
        mGamingApi.fetchArticleDetails(news_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<ArticleDetailRes>(mContext) {
                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onNext(ArticleDetailRes articleDetailRes) {
                        showContent();

                        mWebX5.sendMessageToJS("addVideoInfo", articleDetailRes);
                        mArticleDetailRes = articleDetailRes;
                        mTopbar.setMenuText(mArticleDetailRes.isIs_collect() ? "已收藏" : "收藏");
//                        mWebX5.sendMessageToJS("addThreadInfo", mArticleDetailRes);

                    }

                    @Override
                    public void handleError(Throwable e) {
                        showRetry(e.getMessage());
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }



    private void collect() {
        mGamingApi.collect(IndexContentAdapter.ITEM_VIDEO_CONTENT, mArticleDetailRes.getId(), !mArticleDetailRes.isIs_collect())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<String>(mContext) {
                    @Override
                    public void onNext(String s) {
                        mArticleDetailRes.setIs_collect(mArticleDetailRes.isIs_collect() ? 0 : 1);
                        ToastUtil.showSuccess(mArticleDetailRes.isIs_collect() ? "收藏成功" : "取消收藏成功");
                        mTopbar.setMenuText(mArticleDetailRes.isIs_collect() ? "已收藏" : "收藏");
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebX5.destroy();
    }
}
